// @Author miaoqing
// @Date 2024/03/28 15:13:00
// @Desc
package logic

import (
	"core/component/function"
	"core/component/logger"
	"core/component/timer"
	"core/ini"
	"core/network"
	"net"
	"runtime/debug"
	"strconv"
	"sync"
	"time"
)

var (
	server  *Server
	srvOnce sync.Once
)

type Server struct {
	network.Service
	id         string
	kcpServer  *network.KcpServer
	conf       *ini.Config
	timer      *timer.Timer
	kcpSrvID   string
	kcpSrvPort int
	kcpSrvAddr string

	httpSrvID string
	httpAddr  string
	httpPort  int
	//httpHandler *HTTPHandler
}

func ServerInstance() *Server {
	srvOnce.Do(func() {
		server = &Server{
			kcpServer: &network.KcpServer{},
			timer:     timer.NewTimer(),
		}
		server.Impl = server
	})
	return server
}

func (srv *Server) Init(cfg interface{}, processIdx int) {
	c, ok := cfg.(*ini.Config)
	if !ok {
		return
	}
	srv.conf = c
	srv.kcpSrvPort = srv.conf.Server.FrameKcpPort + processIdx
	srv.kcpSrvAddr = srv.conf.Server.FrameKcpIp + ":" + strconv.Itoa(srv.kcpSrvPort)
	srv.kcpServer.Init(srv.kcpSrvAddr)

	srv.httpPort = srv.conf.Server.FrameHttpPort + processIdx
	srv.httpAddr = srv.conf.Server.FrameHttpIp + ":" + strconv.Itoa(srv.httpPort)
	srv.id = strconv.FormatUint(function.IpAddressStringToUint64(srv.httpAddr), 10)

	logger.Infof("FrameID:%v pidx:%v", srv.id, processIdx)
}
func (srv *Server) Run() {

	srv.kcpServer.NewClient = func(conn net.Conn) network.IConn {
		cli := &Client{
			NetConn: network.NewNetConn(conn, 512*1024),
		}
		cli.Init()
		cli.Impl = cli
		return cli
	}
	go srv.kcpServer.Run()

	go func() {
		tick := time.NewTicker(time.Second * 1)
		defer func() {
			tick.Stop()
			if err := recover(); err != nil {
				logger.Error("[异常] 全局定时器出错", err, "\n", string(debug.Stack()))
			}
		}()
		for {
			select {
			case <-tick.C:
				srv.timer.Loop()
			}
		}
	}()
}

func (srv *Server) Finialize() {}
